import axios from '../../http' // 因为是 js 文件，不能通过 this 拿到 axios
// import router from '../router'

export default {
  namespaced: true,
  state: {
    username: sessionStorage.getItem('username'),
    token: sessionStorage.getItem('token')
  },
  getters: {
  },
  mutations: {
    loginMutation(state, user) {
      state.username = user.username;
      state.token = user.token;
    },
    removeToken(state) {
      state.token = '';
      state.username = '';
    }
  },
  actions: {
    loginAction(context, data) {
      // return axios({
      //   method: 'POST',
      //   url: '/users/login',
      //   data
      // })
      // .then(res => {
      //   console.log('登录请求成功：', res)

      //   if(res.code === 200) {
      //     context.commit('loginMutation', {
      //       token: res.token,
      //       username: data.username
      //     })
      //     // router.push('/');
      //     return Promise.resolve();
      //   }
      // }) 
      // .catch(err => {
      //   console.log('请求错误：', err)
      // })

      return new Promise((resolve, reject) => 
        axios({
          method: 'POST',
          url: '/users/login',
          data
        })
        .then(res => {
          console.log('登录请求成功：', res)

          if(res.code === 200) {
            context.commit('loginMutation', {
              token: res.token,
              username: data.username
            })
            
            // 缓存
            sessionStorage.setItem('token', res.token)
            sessionStorage.setItem('username', data.username)

            resolve();
          }
        }) 
        .catch(err => {
          console.log('请求错误：', err)
          reject()
        })
      )
    },
    removeToken({commit}) {
      commit('removeToken')

      sessionStorage.removeItem('token');
      sessionStorage.removeItem('username');
    }
  },
}